package chapter_3.server;

import chapter_3.VoteService;
import chapter_3.frame.DelimitFramer;
import chapter_3.frame.Framer;
import chapter_3.message.coder.BinaryMessageCoder;
import chapter_3.message.coder.MessageCoder;
import chapter_3.message.entity.RequestMessage;
import chapter_3.message.entity.ResponseMessage;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class VoteTCPServer {
    public static void main(String[] args) throws IOException {
        int listenPort = 8080;
        ServerSocket serverSocket = new ServerSocket(listenPort);
        //创建消息编码/解码器实例，这里使用的是二进制消息编码器，与客户端一致
        MessageCoder binaryMessageCoder = new BinaryMessageCoder();
        //创建一个vote服务实例，用于处理与保存候选人信息与投票信息
        VoteService voteService = new VoteService();
        System.out.println("------------------服务器开始监听-------------------");
        //开始循环监听来自客户端的请求
        while(true){
            Socket clientSocket = serverSocket.accept();

            try (clientSocket) {
                System.out.println("与客户端建立连接，客户端地址为: " + clientSocket.getRemoteSocketAddress());
                //创建一个消息成帧器
                Framer framer = new DelimitFramer(clientSocket.getInputStream());
                byte[] requestByteMsg;
                RequestMessage requestMessage;
                //处理客户端发送来的消息
                while ((requestByteMsg = framer.nextMsg()) != null) {
                    requestMessage = (RequestMessage) binaryMessageCoder.fromWire(requestByteMsg);
                    //处理发送来的请求消息，并生成对应的响应消息
                    ResponseMessage responseMessage = voteService.handleRequest(requestMessage);
                    //将响应消息编码并发送会客户端
                    byte[] responseByteMsg = binaryMessageCoder.toWire(responseMessage);
                    framer.frameMsg(responseByteMsg, clientSocket.getOutputStream());
                }
            } catch (IOException e) {
                System.err.println(e.getMessage());
            }
        }
    }
}
